import { getNow } from '../common/date';

type LogLevel = 'info' | 'warn' | 'error';
type Logger = {
  [key in LogLevel]: Fn<void>;
};

// @ts-ignore
// const { LOG_LEVEL: allowLevel = 'info', DEV: isDev = false } = process.env || {}
const allowLevel = process.env.NEXT_PUBLIC_LOG_LEVEL;
const isDev = process.env.NODE_ENV === 'development';

export function createLogger(prefix = 'msg') {
  const logLevels: Array<LogLevel> = ['info', 'warn', 'error'];
  const colorMap = {
    info: 'blue',
    warn: 'orange',
    error: 'red',
  };
  const allowIndex = logLevels.findIndex(elevel => elevel === allowLevel);
  const logger = {} as Logger;

  logLevels.forEach(level => {
    logger[level] = (...args: any[]) => {
      // 输出日志级别控制
      const index = logLevels.findIndex(elevel => elevel === level);
      if (index < allowIndex) return;
      console.log(
        `%c[${getNow() + ' ' + (level + ':' + prefix).toUpperCase()}]`,
        `color: ${colorMap[level]}`,
        ...args
      );
    };
  });
  return logger;
}
